package com.alibaba.datax.core.transport.transformer;

import cn.hutool.core.util.StrUtil;
import com.alibaba.datax.common.element.Column;
import com.alibaba.datax.common.element.Record;
import com.alibaba.datax.common.element.StringColumn;
import com.alibaba.datax.common.exception.DataXException;
import com.alibaba.datax.core.util.AESUtils;
import com.alibaba.datax.transformer.Transformer;

import java.util.Arrays;



/**
 * @author lizhitao
 **/
public class AESEncryptTransformer extends Transformer {
    public AESEncryptTransformer() {
        super.setTransformerName("dx_aes_encrypt");
    }

    @Override
    public Record evaluate(Record record, Object... paras) {
        int columnIndex;
        String aesKey = null;

        try {
            if (paras.length == 1) {
                columnIndex = (Integer) paras[0];
            } else if (paras.length == 2) {
                columnIndex = (Integer) paras[0];
                aesKey = (String) paras[1];
            } else {
                throw new RuntimeException(getTransformerName() + " paras at moust 2");
            }
        } catch (Exception e) {
            throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_ILLEGAL_PARAMETER, "paras:" + Arrays.asList(paras).toString() + " => " + e.getMessage());
        }


        Column column = record.getColumn(columnIndex);

        try {
            String oriValue = column.asString();
            //如果字段为空，跳过，不进行解密操作
            if (oriValue == null) {
                return record;
            }

            String newValue = "";
            if (StrUtil.isBlank(aesKey)) {
                newValue = AESUtils.encrypt(oriValue, null);
            } else {
                newValue = AESUtils.encrypt(oriValue, aesKey);
            }

            record.setColumn(columnIndex, new StringColumn(newValue));

        } catch (Exception e) {
            throw DataXException.asDataXException(TransformerErrorCode.TRANSFORMER_RUN_EXCEPTION, e.getMessage(), e);
        }

        return record;
    }
}
